import 'package:extended_image/extended_image.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/calendar.dart';
import 'package:geomancy/api/geomancy.dart';
import 'package:geomancy/api/setting.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/models/daily_horsecope_model.dart';
import 'package:geomancy/models/notification_list_model.dart';
import 'package:geomancy/models/record_list_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/event.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_btn.dart';
import 'package:geomancy/widgets/common_loading_circle.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';
import 'package:geomancy/widgets/stroke_text.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  List vipFunctionList = [
    {
      'txt': '自动备份',
      'url': 'assets/icons/icon_vip_cloud.png',
    },
    {
      'txt': '无限择吉',
      'url': 'assets/icons/icon_vip_infinity.png',
    },
    {
      'txt': '去除广告',
      'url': 'assets/icons/icon_vip_ad.png',
    },
    {
      'txt': '更改图标',
      'url': 'assets/icons/icon_vip_widget.png',
    }
  ];

  List<NotificationItemModel> notificationDataList = [];
  List<RecordItemModel> recordDataList = [];
  bool loading = false;
  double progress = 0;  // 进度值 (0 到 1)
  //今日运势
  DailyHoroscopeResult? dailyHoroscopeResult;

  @override
  void initState() {
    super.initState();
    getDailyHoroscope();
    getRecordList();
    getNotificationsList();
    eventListener.on(Constant.REFRESHRECORDLIST, (arg) {
      getRecordList();
    });
  }

  @override
  void dispose() {
    eventListener.off(Constant.REFRESHRECORDLIST);
    super.dispose();
  }

  ///获取今日运势
  Future getDailyHoroscope() async {
    final user = context.read<UserProvider>().getUserInfo;
    if (user?.birthday != null || user?.birthday != '') {
      final zodiacIndex = Utils.getZodiacIndex(user!.birthday!.split(' ')[0]);
      final result = await CalendarAPI.getDailyHoroscope(context, Utils.getZodiacPinYinBybIndex(zodiacIndex));
      if (result != null) {
        final total = result.wealthHoroscope!.star! + result.loveHoroscope!.star! + result.careerHoroscope!.star!;
        setState(() {
          dailyHoroscopeResult = result;
          progress = total / 15;
        });
      }
    }
  }
  ///获取堪舆历史记录
  Future getRecordList() async {
    final result = await GeomancyAPI.getRecordList(context: context, page: CommonPage(page: 1, size: 4));
    setState(() {
      recordDataList = result?.list ?? [];
    });
  }
  ///获取系统通知消息列表
  Future getNotificationsList() async {
    try {
      setState(() {
        loading = true;
      });
      final result = await SettingAPI.getSettingMsgList(context, CommonPage(page: 1, size: 5));
      setState(() {
        notificationDataList = result?.list ?? [];
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  void goTo(String path) {
    context.push(path);
  }

  ///根据type转化成文本
  String getTypeText(String type) {
    switch (type) {
      case '1':
      case '2':
        return '财位运';
      case '3':
      case '4':
        return '人缘位';
      case '5':
      case '6':
        return '文昌位';
      case '7':
        return '安康位';
      default:
        return '';
    }
  }
  CompassSource getCompassSource(String type) {
    switch (type) {
      case '1':
        return CompassSource.roomWealth;
      case '2':
        return CompassSource.stationWealth;
      case '3':
        return CompassSource.roomRelations;
      case '4':
        return CompassSource.stationRelations;
      case '5':
        return CompassSource.roomStudy;
      case '6':
        return CompassSource.stationStudy;
      case '7':
        return CompassSource.health;
      default:
        return CompassSource.roomWealth;
    }
  }

  void goRecordDetail(RecordItemModel item) {
    if (item.type == '1' || item.type == '2') {
      context.push('/wealth_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!)
      });
    } else if (item.type == '3' || item.type == '4') {
      context.push('/relations_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
      });
    } else if (item.type == '5' || item.type == '6') {
      context.push('/study_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
      });
    } else {
      context.push('/health_result', extra: {
        "source": getCompassSource(item.type!),
        "direction": double.parse(item.deg!),
        "birthday": item.birthday,
        "sex": item.sex,
      });
    }
  }

  ///运势item
  Widget rowItem({required String txt, required String url, int num = 0}) {
    return Row(
      children: [
        Expanded(child: StrokeText(txt: txt, fontSize: 24.sp, letterSpacing: 1.5)),
        Wrap(
          spacing: 10.w,
          children: List.filled(5, 0).asMap().keys.map((index) {
            return SizedBox(
              width: 27.w,
              height: 22.w,
              child: Image.asset(index < num ? '${url}_active.png' : '$url.png', height: 22.w),
            );
          }).toList(),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final user = context.watch<UserProvider>().getUserInfo;
    final isVIP = user?.vipTime != null;
    String? zodiac;
    int? zodiacIndex;
    if (user != null && user.birthday != null) {
      zodiacIndex = Utils.getZodiacIndex(user.birthday!.split(' ')[0]);
      zodiac = Utils.getZodiacTxtBybIndex(zodiacIndex);
    }
    return Scaffold(
      backgroundColor: ColorStyle.pageDefaultColor,
      body: ListView(
        physics: const ClampingScrollPhysics(),
        padding: EdgeInsets.all(Constant.PAGEPADDING.w),
        children: [
          SafeArea(
            child: Row(
              children: <Widget>[
                ///头像
                Container(
                  width: 110.w,
                  height: 110.w,
                  margin: EdgeInsets.only(right: 30.w),
                  decoration: BoxDecoration(
                      color: ColorStyle.themeLightColor,
                      border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                      borderRadius: BorderRadius.all(Radius.circular(55.w))
                  ),
                  child: user?.avatar != null
                      ? ClipRRect(borderRadius: BorderRadius.all(Radius.circular(55.w)), child: ExtendedImage.network(user!.avatar!, fit: BoxFit.fill))
                      : null,
                ),
                Expanded(child: GestureDetector(
                  onTap: () {
                    Utils.getLoginState(context);
                  },
                  child: Container(
                    color: Colors.transparent,
                    height: 110.w,
                    alignment: Alignment.centerLeft,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CommonText(txt: user?.username ?? '立即登录', weight: FontWeight.bold),
                        if (isVIP)
                          Row(
                            children: [
                              Container(
                                width: 56.w,
                                height: 26.w,
                                alignment: Alignment.center,
                                margin: EdgeInsets.only(right: 10.w),
                                decoration: BoxDecoration(
                                  color: ColorStyle.borderColor,
                                  borderRadius: BorderRadius.all(Radius.circular(13.w)),
                                ),
                                child: Text('VIP', style: TextStyle(fontSize: 20.sp, color: const Color.fromRGBO(255, 195, 54, 1)),),
                              ),
                              CommonText(txt: '有效期至${user?.vipTime?.split(' ')[0]??'-'}', fontSize: 20.sp),
                            ],
                          )
                      ],
                    ),
                  ),
                )),
                GestureDetector(
                  onTap: () {
                    if (Utils.getLoginState(context)) {
                      goTo('/setting');
                    }
                  },
                  child: Container(
                    width: 80.w,
                    height: 80.w,
                    color: Colors.transparent,
                    alignment: Alignment.centerRight,
                    child: Image.asset('assets/icons/icon_setting.png', width: 40.w,),
                  ),
                )
              ],
            ),
          ),
          Container(
            height: 328.w,
            margin: EdgeInsets.only(top: 40.w, bottom: 40.w),
            padding: EdgeInsets.fromLTRB(34.w, 45.w, 34.w, 0),
            decoration: BoxDecoration(
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w)),
              gradient: const LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color.fromRGBO(255, 195, 54, 1),
                  Color.fromRGBO(255, 232, 198, 1)
                ]
              ),
            ),
            child: Column(
              children: [
                Row(
                  children: [
                    Image.asset('assets/icons/icon_vip.png', height: 29.w),
                    const Expanded(child: CommonText(txt: '尊享豪华特权', weight: FontWeight.bold)),
                    // CommonBtnWidget(
                    //   size: Size(200.w, 60.w),
                    //   child: Row(
                    //     mainAxisAlignment: MainAxisAlignment.center,
                    //     children: [
                    //       CommonText(txt: '立即查看', fontSize: 30.sp),
                    //       SizedBox(width: 6.w),
                    //       Image.asset('assets/icons/icon_arrow_right.png', width: 10.w)
                    //     ],
                    //   ),
                    //   onTap: () {
                    //     context.push('/vip');
                    //   }
                    // )
                  ],
                ),
                SizedBox(height: 42.w),
                Wrap(
                  spacing: 10.w,
                  children: vipFunctionList.asMap().keys.map((index) {
                    return Container(
                      key: ValueKey(index),
                      width: 140.w,
                      height: 140.w,
                      decoration: BoxDecoration(
                        color: ColorStyle.themeLightColor,
                        borderRadius: BorderRadius.all(Radius.circular(20.w)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.3),
                            offset: const Offset(0, 2),
                            blurRadius: 0,
                            spreadRadius: 0,
                          ),
                        ],
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(vipFunctionList[index]['url'], width: 60.w),
                          CommonText(txt: vipFunctionList[index]['txt'], fontSize: 24.sp)
                        ],
                      ),
                    );
                  }).toList(),
                )
              ],
            ),
          ),
          const CommonTitleWidget(txt: '今日运势'),
          GestureDetector(
            onTap: () {
              if (Utils.getLoginState(context)) {
                context.push('/animal_luck', extra: {
                  "animalIndex": zodiacIndex
                });
              }
            },
            child: Container(
              height: 300.w,
              margin: EdgeInsets.only(top: 20.w, bottom: 40.w),
              padding: EdgeInsets.symmetric(horizontal: 35.w),
              decoration: BoxDecoration(
                  color: ColorStyle.themeLightColor,
                  border: Border.all(width: 5.w, color: ColorStyle.borderColor),
                  borderRadius: BorderRadius.all(Radius.circular(60.w))
              ),
              child: Row(
                children: [
                  Container(
                    width: 208.w,
                    height: 208.w,
                    margin: EdgeInsets.only(right: 70.w),
                    child: Stack(
                      children: [
                        PieChart(
                          PieChartData(
                            borderData: FlBorderData(show: false),  // 不显示边框
                            sectionsSpace: 0,  // 每个区域之间的间距为0，保证形成圆环
                            centerSpaceRadius: 48,  // 圆心半径，形成圆环的效果
                            startDegreeOffset: 270,
                            sections: [
                              PieChartSectionData(
                                value: progress * 100,  // 进度值 (百分比)
                                color: ColorStyle.pageDefaultColor,  // 进度条颜色
                                title: '',
                                radius: 12,  // 外圈半径
                                showTitle: false,
                              ),
                              PieChartSectionData(
                                value: (1 - progress) * 100,  // 剩余部分
                                color: ColorStyle.borderColor,  // 剩余部分颜色
                                title: '',
                                radius: 12,  // 外圈半径
                                showTitle: false,
                              ),
                            ],
                          ),
                        ),
                        Center(
                          child: StrokeText(txt: zodiac ?? '', fontSize: 100.sp, fontFamily: 'fontZKKLT'),
                        )
                      ],
                    ),
                  ),
                  Expanded(child: SizedBox(
                    height: 208.w,
                    width: double.infinity,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            CommonText(txt: '查看', fontSize: 24.sp),
                            SizedBox(width: 6.w),
                            Image.asset('assets/icons/icon_arrow_right.png', width: 10.w)
                          ],
                        ),
                        rowItem(txt: '财富运势', num: dailyHoroscopeResult?.wealthHoroscope?.star??0, url: 'assets/icons/icon_luck_wealth'),
                        rowItem(txt: '感情运势', num: dailyHoroscopeResult?.loveHoroscope?.star??0, url: 'assets/icons/icon_luck_emotion'),
                        rowItem(txt: '事业运势', num: dailyHoroscopeResult?.careerHoroscope?.star??0, url: 'assets/icons/icon_luck_cause'),
                      ],
                    ),
                  ))
                ],
              ),
            ),
          ),
          const CommonTitleWidget(txt: '历史记录'),
          Container(
            width: double.infinity,
            height: 200.w,
            margin: EdgeInsets.only(top: 20.w, bottom: 40.w),
            padding: EdgeInsets.only(left: 34.w),
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(50.w)),
            ),
            child: recordDataList.isNotEmpty
              ? Wrap(
                alignment: WrapAlignment.start,
                spacing: 22.w,
                children: [
                  ...recordDataList.asMap().keys.map((index) {
                    final dateStr = recordDataList[index].createTime?.split(' ')[0];
                    final date = '${dateStr?.split('-')[1]}-${dateStr?.split('-')[2]}';
                    return GestureDetector(
                      onTap: () {
                        goRecordDetail(recordDataList[index]);
                      },
                      child: Column(
                        key: ValueKey(index),
                        children: [
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              color: ColorStyle.themeColor,
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: CommonText(txt: getTypeText(recordDataList[index].type!), fontSize: 26.sp),
                          ),
                          SizedBox(height: 14.w),
                          CommonText(txt: date??'-', fontSize: 24.sp)
                        ],
                      ),
                    );
                  }).toList(),
                  GestureDetector(
                    onTap: () {
                      context.push('/record_list');
                    },
                    child: Column(
                      children: [
                        Container(
                          width: 100.w,
                          height: 100.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            color: ColorStyle.themeColor,
                            border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                            borderRadius: BorderRadius.all(Radius.circular(50.w)),
                          ),
                          child: CommonText(txt: '更多', fontSize: 26.sp),
                        ),
                        SizedBox(height: 14.w),
                        CommonText(txt: '', fontSize: 16.sp)
                      ],
                    ),
                  )
                ],
              )
              : Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Wrap(
                        alignment: WrapAlignment.start,
                        spacing: 22.w,
                        children: [
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: const CommonText(txt: '...'),
                          ),
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: const CommonText(txt: '...'),
                          ),
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: const CommonText(txt: '...'),
                          ),
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: const CommonText(txt: '...'),
                          ),
                          Container(
                            width: 100.w,
                            height: 100.w,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              border: Border.all(width: 3.w, color: ColorStyle.borderColor),
                              borderRadius: BorderRadius.all(Radius.circular(50.w)),
                            ),
                            child: const CommonText(txt: '...'),
                          )
                        ],
                      ),
                    SizedBox(height: 14.w),
                    CommonText(txt: '暂无历史记录，请前往主页开始。', fontSize: 20.sp)
                  ],
                )
          ),
          const CommonTitleWidget(txt: '系统消息'),
          Container(
            width: double.infinity,
            margin: EdgeInsets.only(top: 20.w),
            padding: EdgeInsets.symmetric(horizontal: 35.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(50.w)),
            ),
            child: loading ? Container(
              padding: EdgeInsets.symmetric(vertical: 50.w),
              child: const CommonLoadingCircleWidget(),
            ) : (
              notificationDataList.isNotEmpty ? Column(
                children: [
                  ...notificationDataList.map((item) {
                    return GestureDetector(
                      onTap: () {
                        context.push('/system_message_detail', extra: {
                          'id': item.id
                        });
                      },
                      child: Container(
                        key: ValueKey(item.id),
                        height: 110.w,
                        padding: EdgeInsets.only(bottom: 10.w),
                        decoration: BoxDecoration(
                            border:  Border(
                                bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor)
                            )
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Image.asset('assets/icons/icon_notification.png', height: 30.w),
                                SizedBox(width: 6.w,),
                                Expanded(child: CommonText(txt: item.title??'')),
                                CommonText(txt: item.createdAt?.split(' ')[0]??'-', fontSize: 26.sp),
                              ],
                            ),
                            SizedBox(height: 5.w),
                            Text(item.content??'-', maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 26.sp, color: ColorStyle.textColor),)
                          ],
                        ),
                      ),
                    );
                  }).toList(),
                  GestureDetector(
                    onTap: () {
                      context.push('/system_message_list');
                    },
                    child: Container(
                      height: 120.w,
                      alignment: Alignment.center,
                      color: Colors.transparent,
                      child: CommonText(txt: '查看更多', fontSize: 26.sp),
                    ),
                  )
                ],
              ) : Container(
                padding: EdgeInsets.symmetric(vertical: 50.w),
                alignment: Alignment.center,
                child: const CommonText(txt: '暂无系统消息'),
              )
            ),
          ),
        ],
      ),
    );
  }
}
